//
//  PedometerHelper.swift
//  JTYP
//
//  Created by Groot on 2017/12/1.
//  Copyright © 2017年 inspur. All rights reserved.
//

import CoreMotion

class PedometerHelper {

    static let sharedInstance = PedometerHelper()
    private let pedometer = CMPedometer()
    
    private init() {
    }
    
    //let DaysOfInfo = 7
    var motionData: [CMPedometerData]?
    
    func startUpdates(handler: @escaping CMPedometerHandler) {
        let cdate = Calendar.current.startOfDay(for: Date())
        pedometer.startUpdates(from: cdate, withHandler: handler)
    }
    
    // 停止更新
    func StopUpdates() {
        pedometer.stopUpdates()
    }
    
    // 获取当天到目前为止的运动记录
    func dataOfToday(handler: @escaping CMPedometerHandler) {
        let cdate = Calendar.current.startOfDay(for: Date())
        pedometer.queryPedometerData(from: cdate, to: Date.init(timeIntervalSinceNow: 0), withHandler: handler)
    }
    
    // 获取过去7天的所有运动记录
//    func dataOfWeek(handler: @escaping ([(Date, CMPedometerData?)]) -> Void) {
//        if(CMPedometer.isStepCountingAvailable()){
//            var dataOfWeek: [(Date, CMPedometerData?)] = []
//
//            for i in 0...DaysOfInfo-1 {
//                self.pedometer.queryPedometerData(from: getDate(ago: i - 1), to: getDate(ago: i), withHandler: {[unowned self] (data, error) in
//                    dataOfWeek.append((self.getDate(ago: i), data))
//                        if i == self.DaysOfInfo-1 {
//                            handler(dataOfWeek)
//                        }
//                })
//            }
//        }
//    }
    
    func getDate(ago: Int) -> Date{
        var date = Calendar.current.date(byAdding: .day, value: -ago, to: Date())
        date = Calendar.current.startOfDay(for: date!)
        
        return date!
    }
    
}
